package com.party.admin.biz.system;

import com.google.common.collect.Lists;
import com.party.core.utils.MyBeanUtils;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.MemberGroupInfo;
import com.party.core.model.partner.MemberPartner;
import com.party.core.model.system.*;
import com.party.core.service.member.IMemberGroupInfoService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.sign.IMemberSignService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName MemberGroupBizService
 * @Description 机构数据业务处理
 * @Author yifeng
 * @Date 2019/9/26 10:15
 **/
@Service
public class MemberGroupBizService {
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IMemberSysRoleService memberSysRoleService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMemberSetService memberSetService;
    @Autowired
    private IMemberPartnerService memberPartnerService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;
    @Autowired
    private IMemberSignService memberSignService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 保存合作商账号信息
     *
     * @param memberGroup
     * @author yifeng
     * @date 10:48 2019/9/26
     **/
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void savePartnerBiz(MemberGroup memberGroup, Integer type) throws Exception {
        boolean isNew = false;
        if (StringUtils.isEmpty(memberGroup.getId())) {
            isNew = true;
            // 新增
            String realname = memberGroup.getRealname();
            if (StringUtils.isNotBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                memberGroup.setRealname(realname);
                memberGroup.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            memberGroup.setDeployType(0);
            memberGroup.setType(Constant.MEMBER_ORGANIZATION);
            memberGroup.setIsPartner(YesNoStatus.YES.getCode());

            memberGroupService.insert(memberGroup);
        } else {
            // 从数据库取出记录的值
            MemberGroup t = memberGroupService.get(memberGroup.getId());

            // 将编辑表单中的非NULL值覆盖数据库记录中的值
            MyBeanUtils.copyBeanNotNull2Bean(memberGroup, t);

            String realname = t.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                t.setRealname(realname);
                t.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            t.setIsPartner(YesNoStatus.YES.getCode());
            memberGroupService.update(t);
            memberGroup = t;
        }

        List<SysRole> sysRoles = Lists.newArrayList();
        String systemRole = "";

        if (memberGroup.getIsPartner() != null && memberGroup.getIsPartner() == 1) {
            systemRole = RoleEnum.PARTNER_ROLE.getCode();

            if (isNew && type != null && Integer.valueOf("1").equals(type)) {
                // 合作商经典版
                String businessRole = RoleEnum.PARTNER_2_ROLE.getCode();
                SysRole sysRole = sysRoleService.getRole(businessRole, RoleType.PARTNER_ROLE.getCode());
                sysRoles.add(sysRole);
            }
        }
        //一级子账号，自动添加oneLevelChild系统角色
        if (type != null && Integer.valueOf("1").equals(type)) {
            SysRole sysRole = sysRoleService.getRole("oneLevelChild", RoleType.SYSTEM_ROLE.getCode());
            sysRoles.add(sysRole);
        }
        // 分配系统角色
        if (StringUtils.isNotEmpty(systemRole)) {
            SysRole sysRole = sysRoleService.getRole(systemRole, RoleType.SYSTEM_ROLE.getCode());
            sysRoles.add(sysRole);
        }

        for (SysRole sysRole : sysRoles) {
            MemberSysRole memberSysRole = memberSysRoleService.findByMemberAndRole(memberGroup.getId(), sysRole.getId());
            if (null == memberSysRole) {
                memberSysRole = new MemberSysRole();
                memberSysRole.setMemberId(memberGroup.getId());
                memberSysRole.setRoleId(sysRole.getId());
                memberSysRoleService.insert(memberSysRole);
            }
        }
    }

    /**
     * 保存合作商的其他信息
     *
     * @param memberPartner
     * @param memberGroupInfo
     * @param memberGroup
     * @return
     * @author yifeng
     * @date 10:41 2019/9/26
     **/
    public void savePartnerOtherBiz(MemberPartner memberPartner, MemberGroupInfo memberGroupInfo, MemberGroup memberGroup) throws Exception {
        memberSetService.initMemberSet(memberGroup.getId());

        // 保存合作商附属信息表
        if (null == memberPartner) {
            memberPartner = new MemberPartner();
        }
        if (null == memberPartner.getPartnerType()) {
            memberPartner.setPartnerType(0);
        }
        memberPartner.setMemberId(memberGroup.getId());

        MemberPartner partner = memberPartnerService.findByMemberId(memberGroup.getId());
        if (null == partner) {
            //admin 添加的客户默认的套餐是众筹
            memberPartner.setSystemType(2);

            memberPartner.setCreateBy(memberGroup.getId());
            memberPartner.setUpdateBy(memberGroup.getId());
            memberPartnerService.insert(memberPartner);
        } else {
            memberPartner.setId(partner.getId());
            memberPartnerService.update(memberPartner);
        }

        //保存合作商附属表  机构app签到
        memberSignService.getSet(memberGroup.getId());

        memberGroupInfo.setMemberId(memberGroup.getId());
        memberGroupInfo.setExpirationTime(DateUtils.parse(memberGroupInfo.getStringExpirationTime(), "yyyy-MM-dd HH:mm"));

        if (StringUtils.isNotEmpty(memberGroupInfo.getStrSigningTime())) {
            memberGroupInfo.setSigningTime(DateUtils.parse(memberGroupInfo.getStrSigningTime(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotEmpty(memberGroupInfo.getStrContractStartTime())) {
            memberGroupInfo.setContractStartTime(DateUtils.parse(memberGroupInfo.getStrContractStartTime(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotEmpty(memberGroupInfo.getStrContractEndTime())) {
            memberGroupInfo.setContractEndTime(DateUtils.parse(memberGroupInfo.getStrContractEndTime(), "yyyy-MM-dd HH:mm"));
        }

        Double withdrawalCharge = memberGroupInfo.getWithdrawalCharge();
        if (null != withdrawalCharge && 0 != withdrawalCharge) {

            if (!(withdrawalCharge > 0 && withdrawalCharge < 100)) {
                throw new Exception("用户保存异常,请输入正确的提现金额");
            }
            withdrawalCharge = BigDecimalUtils.div(withdrawalCharge, 100, 2);
            memberGroupInfo.setWithdrawalCharge(withdrawalCharge);
        }
        MemberGroupInfo mgi = memberGroupInfoService.findByMemberId(memberGroup.getId());
        if (null == mgi) {
            memberGroupInfoService.insert(memberGroupInfo);
        } else {
            memberGroupInfoService.update(memberGroupInfo);
        }

        String key = "EXPIRE_DATE_" + memberGroup.getId();
        stringJedis.setValue(key, DateUtils.formatDate(memberGroupInfo.getExpirationTime(), "yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 检查账号信息是否存在
     *
     * @param memberGroup 用户信息
     * @return
     * @author yifeng
     * @date 10:44 2019/9/26
     **/
    public String checkAccountInfo(MemberGroup memberGroup) throws Exception {
        List<MemberGroup> mobile = memberGroupService.checkUserName("username", memberGroup.getUsername(),
                memberGroup.getId(), Constant.MEMBER_ORGANIZATION);
        if (mobile != null && mobile.size() > 0) {
            throw new Exception("登录名已存在");
        }

        String oldMemberId = null;
        if (StringUtils.isNotEmpty(memberGroup.getMobile())) {
            mobile = memberGroupService.checkUserName("mobile", memberGroup.getMobile(), memberGroup.getId(), Constant.MEMBER_ORGANIZATION);
            if (mobile != null && mobile.size() > 0) {
                if (mobile.size() == 1) {
                    if (StringUtils.isNotEmpty(memberGroup.getId()) && !memberGroup.getId().equals(mobile.get(0).getId())) {
                        throw new Exception("手机号已存在");
                    }
                    boolean hasPartner = sysRoleService.hasRole(mobile.get(0).getId(), RoleEnum.PARTNER_ROLE.getCode());
                    if (hasPartner) {
                        throw new Exception("手机号已存在");
                    } else {
                        oldMemberId = mobile.get(0).getId();
                    }
                } else {
                    throw new Exception("手机号已存在");
                }
            }
        }
        return oldMemberId;
    }

    /**
     * 保存管理员账号信息
     *
     * @param memberGroup
     * @return
     * @author yifeng
     * @date 14:29 2019/9/26
     **/
    public void saveAdminBiz(MemberGroup memberGroup) {
        if (StringUtils.isEmpty(memberGroup.getId())) {
            String realname = memberGroup.getRealname();
            if (StringUtils.isNotBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                memberGroup.setRealname(realname);
                memberGroup.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            memberGroup.setIsAdmin(YesNoStatus.YES.getCode());
            memberGroup.setType(Constant.MEMBER_PLATFORM);
            memberGroupService.insert(memberGroup);
        } else {
            MemberGroup t = memberGroupService.get(memberGroup.getId());
            try {
                MyBeanUtils.copyBeanNotNull2Bean(memberGroup, t);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String realname = t.getRealname();
            if (StringUtils.isNoneBlank(realname)) {
                realname = PinyinUtil.filterEmoji(realname, "");
                t.setRealname(realname);
                t.setPinyin(PinyinUtil.hanziToPinyin(realname, ""));
            }
            memberGroupService.update(t);
        }
    }

    /**
     * 根据手机号生成合作渠道用户
     *
     * @param mobile      手机号
     * @param countryCode 区号
     * @return 用户id
     */
    public String saveCosponsorMember(String mobile, String countryCode) {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole(RoleEnum.COSPONSOR_ROLE.getCode()));
        if (sysRole == null) {
            throw new BusinessException("角色不存在");
        }

        MemberGroup memberGroup = new MemberGroup();
        memberGroup.setMobile(mobile);
        memberGroup.setCountryCode(countryCode);
        memberGroup.setIsCosponsor(YesNoStatus.YES.getCode());
        memberGroup.setIsAdmin(YesNoStatus.NO.getCode());
        memberGroup.setIsPartner(YesNoStatus.NO.getCode());
        memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
        memberGroup.setType(Constant.MEMBER_ORGANIZATION);
        memberGroupService.insert(memberGroup);

        MemberSysRole memberSysRole = new MemberSysRole();
        memberSysRole.setMemberId(memberGroup.getId());
        memberSysRole.setRoleId(sysRole.getId());
        memberSysRoleService.insert(memberSysRole);
        return memberGroup.getId();
    }

    /**
     * 绑定合作渠道角色
     *
     * @param member 用户
     */
    public void bindCosponsorRole(MemberGroup member) {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole(RoleEnum.COSPONSOR_ROLE.getCode()));
        if (sysRole == null) {
            throw new BusinessException("角色不存在");
        }

        if (!YesNoStatus.YES.getCode().equals(member.getIsCosponsor())) {
            member.setIsCosponsor(YesNoStatus.YES.getCode());
            memberGroupService.update(member);
        }

        boolean hasRole = sysRoleService.hasRole(member.getId(), sysRole.getCode());
        if (!hasRole) {
            MemberSysRole memberSysRole = new MemberSysRole();
            memberSysRole.setMemberId(member.getId());
            memberSysRole.setRoleId(sysRole.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveThirdMember() {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole("", "third_member_manager"));
        if (sysRole == null) {
            sysRole = new SysRole();
            sysRole.setType(2);
            sysRole.setCode("third_member_manager");
            sysRole.setName("第三方用户");
            sysRole.setDelFlag("1");
            sysRoleService.insert(sysRole);
        }
        MemberGroup memberGroup = memberGroupService.getThirdMemberManage();
        if (memberGroup == null) {
            memberGroup = new MemberGroup();
            memberGroup.setUsername("thirdMemberManage");
            memberGroup.setRealname("第三方用户管理员");
            memberGroup.setDelFlag("1"); // 不显示在列表
            memberGroup.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            memberGroup.setType(Constant.MEMBER_ORGANIZATION);
            // 合作商
            memberGroup.setIsPartner(YesNoStatus.NO.getCode());
            // 管理员
            memberGroup.setIsAdmin(YesNoStatus.NO.getCode());
            // 合作渠道
            memberGroup.setIsCosponsor(YesNoStatus.NO.getCode());
            memberGroupService.insert(memberGroup);
        }

        boolean result = sysRoleService.hasRole(memberGroup.getId(), sysRole.getCode());
        if (!result) {
            MemberSysRole memberSysRole = new MemberSysRole(memberGroup.getId(), sysRole.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }

    /**
     * 取消合作商
     *
     * @param memberId 用户id
     * @author yifeng
     * @date 16:19 2019/10/8
     **/
    public void cancelPartner(String memberId) {
        MemberGroup member = memberGroupService.get(memberId);
        member.setIsPartner(0);
        memberGroupService.update(member);
        SysRole partnerRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
        SysRole oneLevelRole = sysRoleService.getRole(RoleEnum.ONE_LEVEL_CHILD.getCode(), RoleType.SYSTEM_ROLE.getCode());
        List<SysRole> sysRoles1 = sysRoleService.findByMemberId(member.getId(), RoleType.BUSINESS_ROLE.getCode());
        List<SysRole> sysRoles2 = sysRoleService.findByMemberId(member.getId(), RoleType.PARTNER_ROLE.getCode());
        List<SysRole> sysRoles = Lists.newArrayList();
        sysRoles.addAll(sysRoles1);
        sysRoles.addAll(sysRoles2);
        sysRoles.add(partnerRole);
        sysRoles.add(oneLevelRole);
        for (SysRole sysRole : sysRoles) {
            memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), member.getId());
        }
    }

    /**
     * 解绑合作渠道角色
     *
     * @param cosponsorId 用户id
     * @author yifeng
     * @date 14:26 2019/10/8
     **/
    public void unBindCosponsorRole(String cosponsorId) {
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole(RoleEnum.COSPONSOR_ROLE.getCode()));
        if (sysRole == null) {
            throw new BusinessException("角色不存在");
        }

        MemberGroup member = memberGroupService.get(cosponsorId);
        member.setIsCosponsor(YesNoStatus.NO.getCode());
        memberGroupService.update(member);

        boolean hasRole = sysRoleService.hasRole(member.getId(), sysRole.getCode());
        if (hasRole) {
            memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), cosponsorId);
        }
    }

    /**
     * 设置合作商
     *
     * @param memberId 用户id
     * @author yifeng
     * @date 16:53 2019/10/8
     **/
    public void addPartner(String memberId, boolean isOneLevel) {
        MemberGroup member = memberGroupService.get(memberId);
        if (!YesNoStatus.YES.getCode().equals(member.getIsPartner())) {
            member.setIsPartner(1);
            memberGroupService.update(member);
        }

        SysRole partnerRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
        memberSysRoleService.getSet(memberId, partnerRole.getId());

        if (isOneLevel) {
            SysRole oneLevelChildRole = sysRoleService.getRole(RoleEnum.ONE_LEVEL_CHILD.getCode(), RoleType.SYSTEM_ROLE.getCode());
            memberSysRoleService.getSet(memberId, oneLevelChildRole.getId());
        }
    }

    /**
     * 添加行知公社角色
     *
     * @param childId 用户id
     * @author yifeng
     * @date 17:03 2019/10/8
     **/
    public void addXzgs(String childId) {
        SysRole partnerRole = sysRoleService.getRole(RoleEnum.KNOWING_COMMUNE_ROLE.getCode(), RoleType.PARTNER_ROLE.getCode());
        memberSysRoleService.getSet(childId, partnerRole.getId());
    }

    /**
     * 行知公社特殊账号
     *
     * @param logo     头像
     * @param username 用户名
     * @param realname 昵称
     * @return
     * @author yifeng
     * @date 14:38 2019/10/22
     **/
    public void saveXzgsSpecialAccount(String logo, String username, String realname) {
        MemberGroup member = memberGroupService.findByUserName(username);
        if (null == member) {
            member = new MemberGroup();
            member.setIsPartner(YesNoStatus.YES.getCode());
            member.setIsAdmin(YesNoStatus.NO.getCode());
            member.setIsCosponsor(YesNoStatus.NO.getCode());
            member.setPassword(PasswordUtils.encryptPassword(Constant.DEFALT_PASSWORD));
            member.setUsername(username);
            member.setRealname(realname);
            member.setLogo(logo);
            member.setType(Member.MEMBER_ORGANIZATION);
            memberGroupService.insert(member);
        }

        //保存合作商附属表  机构app签到
        memberSignService.getSet(member.getId());

        // 添加合作商角色
        SysRole partnerRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
        MemberSysRole memberSysRole = memberSysRoleService.findByMemberAndRole(member.getId(), partnerRole.getId());
        if (null == memberSysRole) {
            memberSysRole = new MemberSysRole();
            memberSysRole.setRoleId(partnerRole.getId());
            memberSysRole.setMemberId(member.getId());
            memberSysRoleService.insert(memberSysRole);
        }

        // 添加合作商角色
        SysRole xzgsRole = sysRoleService.getRole(RoleEnum.KNOWING_COMMUNE_ROLE.getCode(), RoleType.PARTNER_ROLE.getCode());
        memberSysRole = memberSysRoleService.findByMemberAndRole(member.getId(), xzgsRole.getId());
        if (null == memberSysRole) {
            memberSysRole = new MemberSysRole();
            memberSysRole.setRoleId(xzgsRole.getId());
            memberSysRole.setMemberId(member.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }


    /**
     * @Description: 获取行知公社主账号
     * @Param:
     * @return:MemberGroup
     * @Author: Hua Qunhao
     * @Date: 2019/11/12
     */
    public MemberGroup getXingZheGongSheMemberGroup() throws BusinessException {
        SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
        if (xzgsConfig == null || StringUtils.isEmpty(xzgsConfig.getValue())) {
            throw new BusinessException("未设置行知公社主账号id");
        }
        MemberGroup memberGroup = memberGroupService.get(xzgsConfig.getValue());
        if (memberGroup == null) {
            throw new BusinessException("行知公社主账号id设置有误");
        }
        return memberGroup;
    }
}
